package com.andy.common.extend

import android.graphics.Outline
import android.graphics.Rect
import android.os.SystemClock
import android.view.TouchDelegate
import android.view.View
import android.view.ViewOutlineProvider
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import dp


/**
 * 设置单击listener，支持间隔配置
 * @receiver View
 *
 * @param debounceTime Int 两次单击的间隔时长，防止快速频繁点击。默认500毫秒
 * @param onClick Function1<[@kotlin.ParameterName] View, Unit>?
 */
fun View.setOnIMClickListener(debounceTime: Long = 500L, onClick: (View) -> Unit) {
    var lastClickTime = 0L
    this.setOnClickListener {
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastClickTime > debounceTime) {
            lastClickTime = currentTime
            onClick(it)
        }
    }
}

/**
 * 显示键盘
 * @param delayMillis Long 延时展示的时间，不传默认是250毫秒
 *
 */
fun View.showKeyboard(delayMillis: Long? = null) {
    postDelayed({
        isFocusable = true
        isFocusableInTouchMode = true
        requestFocus()
        val inputManager = context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.showSoftInput(this, 0)
    }, delayMillis ?: 0)
}

/**
 * 关闭键盘
 * @param delayMillis Long 延时关闭键盘的时间，不传默认是50毫秒
 *
 */
fun View.hideKeyboard(delayMillis: Long? = null) {
    postDelayed({
        val imm = context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(applicationWindowToken, 0)
        }
    }, delayMillis ?: 0)
}

/**
 * 扩大View 的可点击范围
 * @param vertical 纵向
 * @param horizontal 横向
 * 必须保证parent足够大，如果自定义的范围超出parent的大小，则超出的那部分无效。
 * 一个parent只能设置一个触摸委派，设置多个时，只有最后设置的child有效。如果希望一个view能设置多个委派，需要再自定义parent
 */
fun View.expandTouchSize(vertical: Int = 20.dp, horizontal: Int = 20.dp) {
    val parent = parent as View
    parent.post {
        val rect = Rect()
        this.getHitRect(rect)
        rect.top -= vertical
        rect.bottom += vertical
        rect.left -= horizontal
        rect.right += horizontal
        parent.touchDelegate = TouchDelegate(rect, this)
    }
}

/**
 * 是否在点击区域内
 */
fun View.isInTouchZone(x: Int, y: Int): Boolean {
    val rect = Rect()
    val location = IntArray(2)
    getDrawingRect(rect)
    getLocationOnScreen(location)
    rect.left = location[0]
    rect.top = location[1]
    rect.right += rect.left
    rect.bottom += rect.top
    return rect.contains(x, y)
}

/**
 * 给View设置圆角
 */
fun View.clipRadius(radius: Float) {
    this.outlineProvider = object : ViewOutlineProvider() {
        override fun getOutline(view: View, outline: Outline) {
            outline.setRoundRect(0, 0, view.width, view.height, radius)
        }
    }
    this.clipToOutline = true
}

/**
 * 设置长按事件
 */
fun View.setOnLongClickListener(action: () -> Unit) {
    this.setOnLongClickListener {
        action.invoke()
        true
    }
}